package com.bitter.intceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.bitter.annotation.AutoIde;
import com.bitter.utils.RedisUtils;

import cn.hutool.core.exceptions.ValidateException;

@Component
public class ApiIdeInceptor extends HandlerInterceptorAdapter {

	@Autowired
	private RedisUtils redisTemplate;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// TODO Auto-generated method stub
		if (!(handler instanceof HandlerMethod)) {
			return true;
		}

		final HandlerMethod handlerMethod = (HandlerMethod) handler;

		final Method method = handlerMethod.getMethod();
		// 有这个注解
		boolean methodAnn = method.isAnnotationPresent(AutoIde.class);
		if (methodAnn && method.getAnnotation(AutoIde.class).value()) {
			// 需要实现接口幂等性
			return checkToken(request);

		}
		return super.preHandle(request, response, handler);
	}

	private boolean checkToken(HttpServletRequest request) {

		String token = request.getHeader("token");
		if (StringUtils.isEmpty("token")) {
			token = request.getParameter("token");
			if (StringUtils.isEmpty("token")) {
				throw new ValidateException(0, "参数传入不误，token不存在!");
			}
		}
		if (!redisTemplate.exists(token)) {
			System.out.println("token---->" + token + "----" + redisTemplate.exists(token));
			throw new ValidateException(0, "重复提交!");
		}
		// 返回是否删除成功
		if (!redisTemplate.remove(token)) {
			throw new ValidateException(0, "token删除失败!");
		}
		return true;

	}

}
